import 'dart:convert' as convert;

import 'package:date_format/date_format.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/material.dart' as prefix0;
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:village_android/common/NoKeyboardEditableTextFocusNode.dart';
import 'package:village_android/component/jd_button.dart';
import 'package:village_android/component/member_header.dart';
import 'package:village_android/config/contants.dart';
import 'package:village_android/model/health_submit_model.dart';
import 'package:village_android/model/name_value_model.dart';
import 'package:village_android/model/order_model.dart';
import 'package:village_android/model/stats_model.dart';
import 'package:village_android/model/submit_record_model.dart';
import 'package:village_android/model/user_model.dart';
import 'package:village_android/pages/address/address_list.dart';
import 'package:village_android/pages/health/submit/submit_count.dart';
import 'package:village_android/pages/pay_page.dart';
import 'package:village_android/pages/user/user_list.dart';
import 'package:village_android/utils/common_utils.dart';
import 'package:village_android/utils/http_utlis.dart';

class HealthSubmitDetailPage extends StatefulWidget {
  int healthPaySubmitId;
  UserModel userModel;

  HealthSubmitDetailPage({this.userModel, this.healthPaySubmitId});

  @override
  _HealthSubmitDetailPageState createState() => _HealthSubmitDetailPageState();
}

class _HealthSubmitDetailPageState extends State<HealthSubmitDetailPage> {
  var address = "";
  var reportDate = "";
  var hasRecord = false;

  HealthSubmitModel healthSubmitModel;
  String appealContent;
  int total = 0;
  List healthRentalList = [];
  bool isSubmit = true;

  //费用
  double _totalBeforeFee = 0.00;

  @override
  void initState() {
    refreshData();
    getStatData();
    widget.userModel = CommonUtils.getLocalUserInfo();
    super.initState();
  }

  refreshData() {
    if (widget.healthPaySubmitId != null) {
      getDetail();
    } else {
      getData();
    }
  }

  getData() {
    HttpUtils.get("/sysConfig/list", data: {"dictTypeId": 11}, success: (data) {
      setState(() {
        healthRentalList = data;
        getRecordData();
      });
    }, error: (errorMsg) {
      print(errorMsg);
    });
  }

  getRecordData() {
    HttpUtils.get("/api/submitRecord/detail", data: {"status":0}, success: (data) {
      setState(() {
        SubmitRecordModel submitRecordModel = SubmitRecordModel.fromJson(data);
        if (submitRecordModel != null) {

          var rentalData = convert.jsonDecode(submitRecordModel.healthRentalList);
          healthRentalList = rentalData["data"];
          hasRecord = true;
        }
      });
    }, error: (errorMsg) {
      print(errorMsg);
    });
  }

  getStatData() {
    HttpUtils.get("/api/healthPaySubmit/stats", data: {}, success: (data) {
      StatsModel statsModel = StatsModel.fromJson(data);
      setState(() {
        if (statsModel.field == "total") {
          _totalBeforeFee = double.parse(statsModel.value);
        }
      });
    }, error: (errorMsg) {
      print(errorMsg);
    });
  }

  getColor(HealthSubmitModel item) {
    if (item != null) {
      var titleBgColor = Colors.red;
      if (item.status == K_SUBMIT_NORMAL) {
        titleBgColor = Colors.blueGrey;
      } else if (item.status == K_SUBMIT_ING) {
        titleBgColor = Colors.blue;
      } else if (item.status == K_SUBMIT_SUCCESS) {
        titleBgColor = Colors.green;
      } else if (item.status == K_SUBMIT_FAIL) {
        titleBgColor = Colors.red;
      } else if (item.status == K_APPEAL_ING) {
        titleBgColor = Colors.orange;
      } else if (item.status == K_APPEAL_SUCCESS) {
        titleBgColor = Colors.green;
      } else if (item.status == K_APPEAL_FAIL) {
        titleBgColor = Colors.red;
      } else {
        titleBgColor = Colors.green;
      }
      return titleBgColor;
    }
  }

  getDetail() {
    Map<String, dynamic> data = new Map();
    if (widget.healthPaySubmitId != null) {
      data["healthPaySubmitId"] = widget.healthPaySubmitId;
    }
    HttpUtils.get("/api/healthPaySubmit/detailItem", data: data,
        success: (result) {
      setState(() {
        healthSubmitModel = HealthSubmitModel.fromJson(result);
        if (healthSubmitModel != null) {
          if (healthSubmitModel.status != K_SUBMIT_NORMAL) {
            isSubmit = false;
            if (healthSubmitModel.status == K_SUBMIT_SUCCESS ||
                healthSubmitModel.status == K_APPEAL_SUCCESS) {
              isSubmit = true;
            }
          }
        }
        if (healthSubmitModel.healthRentalList != null) {
          var rentalData =
              convert.jsonDecode(healthSubmitModel.healthRentalList);
          healthRentalList = rentalData["data"];
          total = calTotal();
        }

        address = healthSubmitModel.address;
        reportDate = healthSubmitModel.reportDate;
      });
    }, error: (errorMsg) {
      print(errorMsg);
    });
  }

  Widget initAddress() {
    return Container(
        padding: EdgeInsets.only(left: 20.0),
        child: TextField(
          enabled: healthSubmitModel == null,
          controller: TextEditingController()..text = address,
          focusNode: NoKeyboardEditableTextFocusNode(),
          onTap: (() async {
            var page = AddressListPage();
            var result = await Navigator.push(
                context, new MaterialPageRoute(builder: (context) => page));
            if (result != null) {
              setState(() {
                address = result;
              });
            }
          }),
          decoration: new InputDecoration(labelText: '选择地址'),
          onChanged: (value) {},
        ));
  }

  Widget initReportDate() {
    return Container(
        padding: EdgeInsets.only(left: 20.0),
        child: TextField(
          enabled: healthSubmitModel == null,
          controller: TextEditingController()..text = reportDate,
          focusNode: NoKeyboardEditableTextFocusNode(),
          onTap: (() async {
            // 调用函数打开
            showDatePicker(
              context: context,
              locale: prefix0.Locale('zh'),
              initialDate: new DateTime.now(),
              firstDate:
                  new DateTime.now().subtract(new Duration(days: 360 * 10)),
              // 减 10 年
              lastDate: new DateTime.now()
                  .add(new Duration(days: 360 * 10)), // 加 10 年
            ).then((DateTime val) {
              setState(() {
                reportDate = formatDate(val, [yyyy, '-', mm, '-', dd]);
              });
            }).catchError((err) {
              print(err);
            });
          }),
          decoration: new InputDecoration(labelText: '选择目标日期'),
          onChanged: (value) {},
        ));
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("卫生申请详情"),
        actions: <Widget>[
          new RaisedButton(
              color: Colors.red,
              child: Text(
                "刷新",
                style: TextStyle(color: Colors.white),
              ),
              onPressed: () {
                refreshData();
              }),
        ],
      ),
      body: ListView(
        scrollDirection: Axis.vertical,
        children: <Widget>[
          widget.userModel != null
              ? MemberHeader(
                  userModel: widget.userModel,
                )
              : SizedBox(height: 1),
          SizedBox(height: 5),
          initAddress(),
          SizedBox(height: 5),
          initReportDate(),
          SizedBox(height: 5),
//          getTotalDesc(),
//          getTotal(),
          SizedBox(height: 25),
          Container(
            padding: EdgeInsets.only(left: 15.0),
            child: SizedBox(
              height: 40,
              width: double.infinity,
              child: Text(
                healthSubmitModel != null
                    ? '状态: ' + healthSubmitModel.statusDesc
                    : "未申请，请选择",
                textAlign: TextAlign.left,
                style:
                    TextStyle(color: getColor(healthSubmitModel), fontSize: 16),
              ),
            ),
//            color: Colors.red,
          ),
          AbsorbPointer(
            absorbing: healthSubmitModel != null ? true : (hasRecord == false ? false : true),
            child: ListView.builder(
                itemBuilder: (context, index) {
                  NameValueModel nameValue =
                      NameValueModel.fromJson(healthRentalList[index]);

                  nameValue.number =
                      nameValue.number != null ? nameValue.number : 0;
                  nameValue.value = int.parse(nameValue.value);
                  return _nameValueCell(nameValue);
                },
                shrinkWrap: true,
                physics: new NeverScrollableScrollPhysics(),
                itemCount: healthRentalList.length),
          ),
          Divider(height: 2.0, color: Colors.black38),
          SizedBox(height: 10),
          _getFieldContent(
              "申请拒绝理由",
              (healthSubmitModel != null
                  ? healthSubmitModel.rejectContent
                  : "空")),
          _getFieldContent(
              "申诉理由",
              (healthSubmitModel != null
                  ? healthSubmitModel.appealContent
                  : "空")),
          _getFieldContent(
              "申诉拒绝理由",
              (healthSubmitModel != null
                  ? healthSubmitModel.appealRejectContent
                  : "空")),
          SizedBox(height: 5),
          Container(
            padding: EdgeInsets.only(right: 20.0),
            child: SizedBox(
              height: 40,
              width: double.infinity,
              child: Text(
                '总价: ' + total.toString() + "元",
                textAlign: TextAlign.right,
                style: TextStyle(color: Colors.red, fontSize: 16),
              ),
            ),
//            color: Colors.red,
          ),
        ],
      ),
      bottomNavigationBar: BottomAppBar(
          child: Row(
        children: <Widget>[
          Expanded(
              child: JdButton(
            callBack: () {
              if (healthSubmitModel != null &&
                  healthSubmitModel.status == K_SUBMIT_FAIL) {
                _asyncInputDialog(
                    context, healthSubmitModel.appealRejectContent);
              }
            },
            text: "重新提交审核",
            color: (healthSubmitModel != null &&
                    healthSubmitModel.status == K_SUBMIT_FAIL)
                ? Colors.orange
                : Colors.grey,
          )),
          Expanded(
              child: JdButton(
            callBack: () {
              isSubmit == true
                  ? (healthSubmitModel != null &&
                          (healthSubmitModel.status == K_SUBMIT_SUCCESS ||
                              healthSubmitModel.status == K_APPEAL_SUCCESS))
                      ? showPayPage(context)
                      : showAlertDialog(context)
                  : Navigator.of(context).pop("confirm");
            },
            text: isSubmit == true
                ? (healthSubmitModel != null &&
                        (healthSubmitModel.status == K_SUBMIT_SUCCESS ||
                            healthSubmitModel.status == K_APPEAL_SUCCESS))
                    ? "付款"
                    : "提交"
                : "确认",
            color: Colors.red,
          )),
        ],
      )),
    );
  }

  Widget getTotalDesc() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      child: ListTile(
        onTap: null,
        title: Row(children: <Widget>[
          new Expanded(
              child: new Text("应缴累计（元）",
                  style: TextStyle(
                    fontSize: 14,
                    color: Colors.black,
                  ))),
        ]),
      ),
    );
  }

  Widget getTotal() {
    return Container(
      height: ScreenUtil.getInstance().setHeight(60),
      child: ListTile(
        onTap: null,
        title: Row(children: <Widget>[
          new Expanded(
              child: new Text(_totalBeforeFee.toString(),
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.black,
                  ))),
        ]),
      ),
    );
  }

  Widget _getFieldContent(field, String value) {
    return Container(
      padding: EdgeInsets.only(left: 20.0),
      child: SizedBox(
        height: 80,
        width: double.infinity,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text(
              field,
              textAlign: TextAlign.left,
              style: TextStyle(color: Colors.black, fontSize: 16),
            ),
            SizedBox(height: 10),
            Text(
              value.length == 0 ? "空" : value,
              textAlign: TextAlign.left,
              style: TextStyle(color: Colors.black54, fontSize: 14),
            ),
            SizedBox(height: 10),
            Divider(height: 2.0, color: Colors.black38),
          ],
        ),
      ),
//            color: Colors.red,
    );
  }

  //提交
  Future saveSubmit() async {
    Map<String, dynamic> params = new Map<String, dynamic>();
    String actionURL;
    if (healthSubmitModel == null) {
      params["status"] = 1;
      if (widget.userModel != null) {
        params["userId"] = widget.userModel.userId;
        params["username"] =
            widget.userModel.account + '-' + widget.userModel.name;
      }
      if (address != null) {
        params["address"] = address;
      }
      if (reportDate != null) {
        params["reportDate"] = reportDate;
      }

      Map rentalListData = new Map();
      rentalListData["data"] = this.healthRentalList;
      String rentalJson = convert.jsonEncode(rentalListData);
      params["healthRentalList"] = rentalJson;

      actionURL = "/api/healthPaySubmit/addItem";
    } else {
      if (appealContent != null && healthSubmitModel.status == K_SUBMIT_FAIL) {
        healthSubmitModel.appealContent = appealContent;
      }
      params = healthSubmitModel.toJson();
      actionURL = "/api/healthPaySubmit/editItem";
    }

    FormData formData = new FormData.from(params);
    var dio = new Dio();
    var response = await dio.post(BaseUrl.url + actionURL, data: formData);
    print(response.data.toString());
    var data = response.data;
    if (data["code"] == 200 || data["code"] == 0) {
      CommonUtils.showToast(context, "提交成功");
      if (widget.healthPaySubmitId != null) {
        refreshData();
      } else {
        Navigator.of(context).pop("insert");
      }
    } else {
      CommonUtils.showToast(context, "提交失败");
    }
  }

  //确认
  Future showPayPage(BuildContext context) async {
    OrderModel orderModel = new OrderModel();

    orderModel.amount = (total).toString();
    orderModel.orderId = healthSubmitModel.createTime.toString();
    orderModel.remark = "卫生费缴纳";
    orderModel.title = "卫生费缴纳 - " + healthSubmitModel.createTime;
    orderModel.name = healthSubmitModel.username;
    orderModel.address = healthSubmitModel.address;
    orderModel.targetId = healthSubmitModel.healthPaySubmitId;
    var page = new PayPage(orderModel: orderModel);
    final result = await Navigator.push(
        context, new MaterialPageRoute(builder: (context) => page));
    if (result != null) {
      //更新
      healthSubmitModel.orderId = orderModel.orderId;
      healthSubmitModel.status = K_PAY_DONE;
      saveSubmit();
      refreshData();
    }
  }

  void showAlertDialog(BuildContext context) {
    showDialog(
        context: context,
        builder: (_) => new AlertDialog(
                title: new Text("是否提交"),
                content: new Text(""),
                actions: <Widget>[
                  new FlatButton(
                    child: new Text("取消"),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  new FlatButton(
                    child: new Text("确定"),
                    onPressed: () {
                      Navigator.of(context).pop();
                      saveSubmit();
                    },
                  )
                ]));
  }

  //弹出输入框
  Future<String> _asyncInputDialog(BuildContext context, initValue) async {
    String teamName = initValue;
    return showDialog<String>(
      context: context,
      barrierDismissible: false,
      // dialog is dismissible with a tap on the barrier
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('输入申诉理由'),
          content: new Row(
            children: <Widget>[
              new Expanded(
                  child: new TextField(
                controller: TextEditingController()..text = teamName,
                autofocus: true,
                decoration:
                    new InputDecoration(labelText: '申诉理由', hintText: '如：申诉理由'),
                onChanged: (value) {
                  teamName = value;
                },
              ))
            ],
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text("取消"),
              onPressed: () {
                Navigator.of(context).pop(initValue);
              },
            ),
            FlatButton(
              child: Text('确定'),
              onPressed: () {
                if (teamName.length == 0) {
                  CommonUtils.showToast(context, "不要输入空白");
                  return;
                }
                Navigator.of(context).pop(teamName);
                appealContent = teamName;
                saveSubmit();
              },
            ),
          ],
        );
      },
    );
  }

  //独立Item
  Widget _nameValueCell(item) {
    return new GestureDetector(
//      onTap: () {onItemClick(item);},
      child: Container(
        height: ScreenUtil().setHeight(90),
        alignment: Alignment.center,
        padding: EdgeInsets.all(10.0),
        margin: EdgeInsets.all(10.0),
        color: Colors.white30,
        child: Row(
          children: <Widget>[
            Padding(padding: EdgeInsets.only(left: 15)),
            Expanded(
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Container(
                    width: ScreenUtil.getInstance().setWidth(150),
                    child: Text(
                      item.name,
                      style: TextStyle(color: Colors.black, fontSize: 15.0),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Expanded(
                    child: CountWidget(
                      count: item.number,
                      value: item.value,
                      targetId: item.name,
                      callBack: ((targetId, isIncrease) {
                        increaseOrReduceOperation(targetId, isIncrease);
                      }),
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(right: 30)),
                  Container(
                    width: ScreenUtil.getInstance().setWidth(200),
                    child: Text(
                      "单价: " + item.value.toString() + "元/间",
                      style: TextStyle(color: Colors.black, fontSize: 15.0),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  Padding(padding: EdgeInsets.only(top: 2)),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 增加/减少商品数量
  increaseOrReduceOperation(String targetId, bool isIncrease) {
    int totalPrice = 0;

    for (int i = 0; i < healthRentalList.length; i++) {
      NameValueModel nameValue = NameValueModel.fromJson(healthRentalList[i]);
      if (nameValue.name == targetId) {
        if (isIncrease) {
          nameValue.number += 1;
        } else {
          nameValue.number -= 1;
          if (nameValue.number < 0) {
            nameValue.number = 0;
          }
        }
        healthRentalList[i] = nameValue.toJson();
      }
      totalPrice += int.parse(nameValue.value) * nameValue.number;
    }

    setState(() {
      healthRentalList = healthRentalList;
      total = totalPrice;
    });
  }

  //计算总数
  int calTotal() {
    int totalPrice = 0;

    for (int i = 0; i < healthRentalList.length; i++) {
      NameValueModel nameValue = NameValueModel.fromJson(healthRentalList[i]);
      totalPrice += int.parse(nameValue.value) * nameValue.number;
    }
    return totalPrice;
  }
}
